<template>
  <view class="container">
    <view class="common_cell common_cell2">
      <u-cell-group :border="false">
        <u-cell :border="false" isLink title="头像" @click="handleAvatarClick">
          <view slot="value">
            <u-avatar size="85.227rpx" :src="avatarSrc"></u-avatar>
          </view>
        </u-cell>

        <u-cell :border="false" isLink title="昵称" :value="nickname" @click="openNicknamePopup"> </u-cell>

        <u-cell :border="false" isLink title="退出登陆" @click="layout"> </u-cell>
      </u-cell-group>
    </view>

    <!-- 昵称编辑弹窗 -->
    <u-popup :show="showNicknamePopup" mode="center" :round="12" @close="showNicknamePopup = false">
      <view class="nickname-popup">
        <view class="popup-title">修改昵称</view>
        <u-input v-model="editNickname" placeholder="请输入新的昵称" clearable />
        <view class="popup-actions">
          <u-button class="btn" text="取消" @click="showNicknamePopup = false" />
          <u-button class="btn" type="primary" :loading="savingNickname" text="确认" @click="confirmNickname" />
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { getUserInfo, updateUserInfo, uploadApi } from "@/api/index";
export default {
  components: {},
  data() {
    return {
      // 页面参数
      options: {},
      avatarSrc: "http://pic2.sc.chinaz.com/Files/pic/pic9/202002/hpic2119_s.jpg",
      nickname: "",
      showNicknamePopup: false,
      editNickname: "",
      savingNickname: false,
      _infoFieldKey: "nickname",
      _avatarFieldKey: "avatar",
      uploadingAvatar: false,
    };
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    try {
      const info = await getUserInfo();
      // 兼容不同字段名
      this.nickname = info?.nickname || info?.nickName || info?.name || "";
      this._infoFieldKey = info?.nickname !== undefined
        ? "nickname"
        : info?.nickName !== undefined
          ? "nickName"
          : info?.name !== undefined
            ? "name"
            : "nickname";

      // 头像字段兼容获取
      const avatarKeys = ["avatar", "avatarUrl", "headUrl", "headImg", "portrait", "icon", "photo", "head"];
      const foundKey = avatarKeys.find(k => info && info[k] !== undefined);
      if (foundKey) {
        this._avatarFieldKey = foundKey;
        this.avatarSrc = info[foundKey] || this.avatarSrc;
      }
    } catch (error) {
      // 获取失败不影响页面，其它功能可继续使用
    }
  },

  methods: {
    toMoney() {
      // uni.navigateTo({
      //   url: "/pages/me/money/index",
      // });
      uni.navigateTo({
        url: `/pages/index/recharge/index?type=2`,
      });
    },
    toWarning() {
      uni.navigateTo({
        url: "/pages/me/warning/index",
      });
    },
    layout() {
      uni.navigateTo({
        url: "/pages/login/index",
      });
    },

    openNicknamePopup() {
      this.editNickname = this.nickname || "";
      this.showNicknamePopup = true;
    },

    async confirmNickname() {
      const value = (this.editNickname || "").trim();
      if (!value) {
        uni.$u ? uni.$u.toast("请输入昵称") : uni.showToast({ title: "请输入昵称", icon: "none" });
        return;
      }
      this.savingNickname = true;
      try {
        const payload = { [this._infoFieldKey]: value };
        await updateUserInfo(payload);
        this.nickname = value;
        this.showNicknamePopup = false;
        uni.$u ? uni.$u.toast("昵称已更新") : uni.showToast({ title: "昵称已更新", icon: "none" });
      } catch (error) {
        uni.$u ? uni.$u.toast("更新失败，请稍后重试") : uni.showToast({ title: "更新失败，请稍后重试", icon: "none" });
      } finally {
        this.savingNickname = false;
      }
    },

    async handleAvatarClick() {
      if (this.uploadingAvatar) return;
      try {
        const chooseRes = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: 1,
            sizeType: ["compressed"],
            sourceType: ["album", "camera"],
            success: resolve,
            fail: reject,
          });
        });

        const files = (chooseRes.tempFiles && chooseRes.tempFiles.length > 0)
          ? chooseRes.tempFiles.map(f => ({ path: f.path || f.tempFilePath || f }))
          : (chooseRes.tempFilePaths || []).map(p => ({ path: p }));

        if (!files.length) {
          uni.$u ? uni.$u.toast("未选择图片") : uni.showToast({ title: "未选择图片", icon: "none" });
          return;
        }

        this.uploadingAvatar = true;
        uni.showLoading({ title: "上传中..." });

        const uploadRes = await uploadApi(files);
        let src = null;
        if (Array.isArray(uploadRes)) {
          const first = uploadRes[0];
          src = (first && (first.src || first.url)) || (typeof first === "string" ? first : null);
        } else if (uploadRes && typeof uploadRes === "object") {
          src = uploadRes.src || uploadRes.url || uploadRes.path || null;
        } else if (typeof uploadRes === "string") {
          src = uploadRes;
        }

        if (!src) {
          throw new Error("上传结果缺少图片地址");
        }

        const payload = { [this._avatarFieldKey]: src };
        await updateUserInfo(payload);
        this.avatarSrc = src;
        uni.$u ? uni.$u.toast("头像已更新") : uni.showToast({ title: "头像已更新", icon: "none" });
      } catch (error) {
        const msg = (error && error.message) ? error.message : "上传或更新失败，请稍后重试";
        uni.$u ? uni.$u.toast(msg) : uni.showToast({ title: msg, icon: "none" });
      } finally {
        this.uploadingAvatar = false;
        uni.hideLoading();
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.container {
  background: #f6f7fb;

  padding: 0rpx;
}

.u-cell-left {
  display: flex;
  align-items: center;

  img {
    width: 37.5rpx;
    height: 37.5rpx;
  }

  text {
    margin-left: 34.091rpx;
  }
}

.common_cell {
  background: #fff !important;

  border-radius: 17.045rpx;
  margin-top: 18.75rpx;
  padding-left: 34.091rpx;
  padding-right: 34.091rpx;

  ::v-deep .u-cell__body {
    padding-top: 35.795rpx !important;
  }
}

.nickname-popup {
  width: 560rpx;
  padding: 34rpx;
  box-sizing: border-box;

  .popup-title {
    font-size: 32rpx;
    font-weight: 500;
    margin-bottom: 24rpx;
    text-align: center;
  }

  .popup-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 32rpx;

    .btn {
      width: 48%;
    }
  }
}
</style>